#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>

int main()
{

  while(1)
  {

    printf("[dzp@myshell shell]= ");
    char arr[1024]={0};
    fgets(arr,1024,stdin);
    char *str[24]={0};
    arr[strlen (arr)-1]='\0';
   
    char* parr=arr;
    int cur=0;
    while(*parr!='\0')
    {
      if(*parr=='>')
      {
        cur++;
        *parr='\0';
        parr++;
        if(*parr=='>')
        {
          cur++;
          *parr='\0';
          parr++;
        }
        break;
      }else if(*parr=='<')
      {
        cur=3;
        *parr='\0';
        parr++;
        break;
      }else
      {  
      parr++;
      }
    }

      while(*parr==' ')
      {
        parr++;
      }

      int fd=0;
    if(cur==1)
    {
      fd = open(parr,O_WRONLY);
    }else if(cur==2)
    {
       fd = open(parr,O_WRONLY|O_APPEND);
    }else if(cur==3)
    {
       fd=open(parr,O_RDONLY);
    }
    if(fd<0)
    {
      perror("open");
      return 1;
    }

    str[0]=strtok(arr," ");
    int i=1;
    while(str[i]=strtok(NULL," "))
    {
      i++;
    }
    
    
    pid_t id=fork();
    if(id==0)
    {
      if(cur==1||cur==2)
      {
        dup2(fd,1);
      }else if(cur==3)
      {
        dup2(fd,0);
      }
      execvp(str[0],str);
      exit(11);
    }


    int status=0;
     waitpid(-1,&status,0);
     if(WIFEXITED(status))
      {
        printf("%d\n",WEXITSTATUS(status));
      }

  }

  return 0;
}
